// pages/countdown/countdown.js
import Toast from 'tdesign-miniprogram/toast/index';
var timer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    countdown_time: 99999,
    time: 99999,
    countdown_time_text: '00:00:00',
    sandDuration: 0.4,
    mode: '',
    countdown_minute: '00',
    minute: '00:01',
    countdown: 0,
    countdown_hour: '00',
    countdown_second: '00'
  },
  formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  },
  countdown() {
    let countdown_time = this.data.countdown_time
    let time = this.formatTime(countdown_time)
    if (this.data.countdown_time < 0) {
      return 
    }
    this.setData({
      countdown_time_text: time
    })
    this.setData({
      countdown_time: countdown_time - 1
    })
    timer = setTimeout(this.countdown.bind(this), 1000);
  },
  showPicker(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    console.log(mode)
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    const {
      mode,
      countdown_time
    } = this.data;

    console.log('confim', value);

    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
    });

    let arr = value.split(':');
    let hour = parseInt(arr[0])
    let mintue = parseInt(arr[1])
    let time = hour * 3600 + mintue * 60
    console.log('时间', time)
    if (time == 0) {
      return Toast({
        context: this,
        selector: '#t-toast',
        message: '至少选择一分钟',
        theme: 'error',
      });
    }
    this.setData({
      time,
      countdown_time:time
    })
    this.hidePicker();
    clearTimeout(timer);
    this.countdown()
  },

  onColumnChange(e) {
    console.log('pick', e.detail.value);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  calSpeed() {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})